package jprint.jfx;

import java.awt.Point;
import java.io.File;
import jprint.base.AppContext;
import jprint.base.http.Http;

/**
 * @author zw-zheng
 * Created on 2020-11-22
 */
public class AppContextImpl implements AppContext {

    private static AppContextImpl sInstance;
    private File webRoot;
    private Http.HttpServer server;
    private int printerDPI = 360;
    private int paperWidth = 210; // mm
    private int paperHeight = 297; // mm
    private double scale = 1.0;
    private Point offset = new Point(0, 0);

    private AppContextImpl() {
        webRoot = new File(System.getProperty("user.dir", "."), "webapp");
    }

    public static AppContext getInstance() {
        if (sInstance == null) sInstance = new AppContextImpl();
        return sInstance;
    }

    @Override public File getAppHome() {
        return webRoot.getParentFile();
    }

    @Override public File getWebRoot() {
        return webRoot;
    }

    @Override public void setServer(Http.HttpServer server) {
        this.server = server;
    }

    @Override public int getPrinterDPI() {
        return printerDPI;
    }

    @Override public void setPrinterDPI(int printerDPI) {
        if (printerDPI >= 1 & printerDPI <= 9600) {
            this.printerDPI = printerDPI;
        }
    }

    @Override public int getPaperWidth() {
        return paperWidth;
    }

    @Override public void setPaperWidth(int paperWidth) {
        if (paperWidth >= 10 && paperWidth <= 1000) {
            this.paperWidth = paperWidth;
        }
    }

    @Override public int getPaperHeight() {
        return paperHeight;
    }

    @Override public void setPaperHeight(int paperHeight) {
        if (paperHeight >= 10 && paperHeight <= 1000) {
            this.paperHeight = paperHeight;
        }
    }

    @Override public double getScale() {
        return scale;
    }

    @Override public void setScale(double scale) {
        if (scale > 0 && scale < 4) {
            this.scale = scale;
        }
    }

    @Override public void setOffset(int x, int y) {
        offset = new Point(x, y);
    }

    @Override public Point getOffset() {
        return offset;
    }

    @Override public void exit() {
        if (server != null) server.stop();
    }

    @Override public String toString() {
        return "AppContextImpl{" +
            "\nwebroot=" + webRoot +
            "\nprinterDPI=" + printerDPI +
            "\npaperWidth=" + paperWidth +
            "\npaperHeight=" + paperHeight +
            "\nscale=" + scale +
            "\noffset=" + offset.x + "," + offset.y +
            "\n}";
    }
}
